﻿using System;
using System.Collections.Generic;
using System.IO;
using Common;
using ImageProcessing.Common;
using ImageProcessing.Storage;
using Visualizers.ServerConnecter;
using WcfService.DataContracts;

namespace Visualizers
{
    internal class BackGroundImageDownloader
    {
        private readonly OnlineImageArchiver _onlineImageArchiver;
        public event Action<String> SatusUpdate;
        public event Action<TagInfo> ImageAdded;

        public void RaiseImageAdded(TagInfo tagInfo)
        {
            Action<TagInfo> handler = ImageAdded;
            if (handler != null) handler(tagInfo);
        }

        public event Action DownloadComplete;

        public BackGroundImageDownloader(OnlineImageArchiver onlineImageArchiver)
        {
            _onlineImageArchiver = onlineImageArchiver;
        }

        public void RaiseDownloadComplete()
        {
            Action handler = DownloadComplete;
            if (handler != null) handler();
        }

        private void RaiseSatusUpdate(string status)
        {
            Action<string> handler = SatusUpdate;
            if (handler != null) handler(status);
        }

        internal void AsyncDownload()
        {
            System.Threading.Tasks.Task.Factory.StartNew(BeginDownload);
        }

        internal void BeginDownload()
        {
            try
            {
                wpOrtConnector wpOrtConnector = new wpOrtConnector(IpeRemoteLookup.LocalHost);

                RaiseSatusUpdate("Fetching image List from serer");

                // get list of images
                List<TagInfo> infoMetaData = wpOrtConnector.GetImagesMetaData();


                int imageListCount = infoMetaData.Count;
                int donwloadedCount = 0;

                // download them to disk if they dont exist locally
                foreach (var tagInfo in infoMetaData)
                {
                    donwloadedCount++;
                    RaiseSatusUpdate(string.Format("Downloading Image {0} of {1}", donwloadedCount, imageListCount));

                    if (!File.Exists(tagInfo + HelperMethods.RawFileExtension))
                    {
                        ImageData imageData = wpOrtConnector.DownloadImageData(tagInfo);
                        var uncompressedData = CompressionHelpers.Uncompress(imageData.ZipCompressedYData);
                        _onlineImageArchiver.SaveRawImage(imageData.TagInfo, imageData.Width, imageData.Height, ref uncompressedData);
                    }

                    RaiseImageAdded(tagInfo);

                }

                RaiseSatusUpdate("Downloading of images from server complete");
            }
            catch (Exception exception)
            {
                RaiseSatusUpdate("Download Failed : " + exception.Message);
                return;
            }

            RaiseDownloadComplete();
        }
    }
}
